<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm"  :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文件名称" prop="fileName">
        <el-input v-model="queryParams.fileName" placeholder="请输入文件名称" clearable style="width: 240px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search"  @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh"  @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <!--<el-button
          type="primary"
          plain
          icon="el-icon-plus"

          @click="handleAdd"
        >上传</el-button>-->
        <el-button class="upload_btn" @click="addFile" type="primary" icon="el-icon-upload" style="height: 37px">上传文件</el-button>
        <el-upload v-show="false" multiple action="" :http-request="uploadFileUrl" :before-upload="handleBeforeUpload"
                   :on-error="handleUploadError" :on-exceed="handleExceed"
                   :show-file-list="false" class="upload-file-uploader" ref="fileUpload">
          <el-button class="upload_btn" id="realUpload" type="primary" icon="el-icon-upload" style="height: 37px">上传文件</el-button>
        </el-upload>
      </el-col>
      <!--<el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"

          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>-->
      <el-col :span="1.5"  >
        <el-select v-model="fileMJ" placeholder="请选择密级" clearable >
          <el-option v-for="dict in renyuanOptions" :key="dict.dictValue" :value="dict.dictValue" :label="dict.dictLabel"></el-option>
        </el-select>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"

          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <!--<el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"

          @click="handleExport"
          v-hasPermi="['manage:MODELMANAGE:export']"
        >导出</el-button>
      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :search="false"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="MODELMANAGEList" :height="tableHeight" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" :index="table_index" prop="id" align="center"/>
      <el-table-column label="文件名称" align="center" prop="fileName" />
      <el-table-column label="文件密级" align="center" prop="mj" >
        <template slot-scope="scope">
          {{getChangeType(scope.row.mj)}}<!--调用getChangeType方法-->
        </template>
      </el-table-column>
      <el-table-column label="上传人" align="center" prop="createBy" />
      <el-table-column label="上传时间" align="center" prop="createTime" />

    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

  </div>
</template>

<script>
import { listMODELMANAGE,  delMODELMANAGE ,fileUpload} from "@/api/archive/quanzongjuanguanli/modelmanage";
import {getInfo} from "@/api/login";  //档案树
import estimateTableHeight from "@/mixins/estimateTableHeight";
import CryptoJS from "crypto-js";
import {
  getdamjbyrymj,fbstat
} from "@/api/archive/fileCollection/offlinReception.js";
import { getDicts_archive } from "@/api/archive/dict/dictManageData";
export default {
  archive_Dicts: ['MJ'],
  name: "MODELMANAGE",
  mixins: [estimateTableHeight], // 混入方法
  data() {
    return {
      // 遮罩层
      loading: true,
      chunkSize: 20,
      //limit: 1,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      menuName:"",
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 大事记/组织沿革模板管理表格数据
      MODELMANAGEList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fileName: null,
        PATH: null,
        PREFIX: null,
        type: null,
        isDel: null,
        deptId: null,
        userId: null,
        createBy: null,
        mj: null,
        createTime: null,
        isDel:"0"
      },
      userId: '',
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      renyuanOptions:[],
      fileMJ:undefined,
      isFbState: false,
      typeList:[]
    };
  },
  created() {
    this.menuName = this.$route.meta.title;
    //console.log(this.$route.meta)
    this.queryParams.type = this.menuName.includes("大事记")?1:2;
    this.getList();
    this.getConfigKey("CHUNK_SIZE").then(response => {
      if(response.msg == '') {
        this.chunkSize = 20
      } else {
        this.chunkSize = response.msg
      }
    });
    getInfo().then(response=>{
      this.userId = response.user.userId
    })
    fbstat().then(res => {  //false=不是分保，true=是分保
      this.isFbState = res.data
    })
    getDicts_archive("MJ").then(res => { //人员密级
      this.typeList = res;
      getdamjbyrymj().then(resdata => { //此接口没有返回dictLabel，需要组装接口
        console.log(resdata,'11111');
        console.log(res,'222222');
        var mjdata = [];
        for (var i in resdata.data) {
          for (var j in res.data) {
            //  console.log(resdata.data[i].daMj, res.data.MJ[j].dictValue)
            if (resdata.data[i].daMj == res.data[j].dictValue) {
              mjdata.push(res.data[j])
            }
          }
        }

        this.renyuanOptions = mjdata

      })
    })
  },
  methods: {
    getChangeType(e) {
      for (var i = 0; i < this.typeList.data.length; i++) {
        if (this.typeList.data[i].dictValue == e) { //value，label保持和上面定义一致
          return this.typeList.data[i].dictLabel;
        }
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const IDs = row.ID || this.ids;
      if (IDs==''){
        this.$message({ message: '请选择数据', type: 'warning' });
        return;
      }
      this.$modal.confirm('是否确认删除？').then(function() {
        return delMODELMANAGE(IDs);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    table_index(index) {
      return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
    },
    /** 查询大事记/组织沿革模板管理列表 */
    getList() {
      this.loading = true;
      listMODELMANAGE(this.queryParams).then(response => {
        this.MODELMANAGEList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    addFile(){
      if (this.isFbState){
        if (this.fileMJ == undefined) {
          this.$message.warning(`请选择密级`);
          return false;
        }else{
          $("#realUpload").click();
        }
      }else{
        $("#realUpload").click();
      }
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      const extension = file.name.substring(file.name.lastIndexOf('.') + 1);
      if (extension !== 'doc' && extension !== 'docx') {
        this.$message.warning('只允许上传doc、docx格式的文件')
        return false
      }
      this.$modal.loading("正在上传文件，请稍候...");
      return true;
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError("上传文件失败，请重试");
      this.$modal.closeLoading()
    },
    // 文件个数超出
    handleExceed() {
      //this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    calculateMD5(file) {
      return new Promise((resolve, reject) => {
        const chunkSize = 20 * 1024 * 1024;
        const totalChunks = Math.ceil(file.size / chunkSize); // 总块数
        let currentChunk = 0;
        const fileReader = new FileReader();
        const hashBuffer = [];
        fileReader.onload = function(event) {
          const chunkArray = new Uint8Array(event.target.result);
          hashBuffer.push(chunkArray);
          currentChunk++;
          if (currentChunk < totalChunks) {
            loadNextChunk();
          } else {
            const wordArray = CryptoJS.lib.WordArray.create(hashBuffer.reduce((acc, curr) => acc.concat(curr), []));
            const md5 = CryptoJS.MD5(wordArray).toString();
            file.md5 = md5; // 将计算得到的 MD5 值保存到 file 对象中
            resolve(md5);
          }
        };
        fileReader.onerror = function(event) {
          reject(event.target.error);
        };
        function loadNextChunk() {
          const start = currentChunk * chunkSize;
          const end = Math.min(start + chunkSize, file.size);
          fileReader.readAsArrayBuffer(file.slice(start, end));
        }
        loadNextChunk();
      });
    },
    uploadFileUrl(concent, currentChunk) {
      // 分片处理
      // const chunkSize = 20 * 1024 * 1024; // 每个片段的大小，这里是20MB
      concent.file.chunkSize = this.chunkSize;
      console.log("chunkSize",this.chunkSize)
      const totalChunks = Math.ceil(concent.file.size / (this.chunkSize * 1024 * 1024)); // 总片段数
      console.log("totalChunks",totalChunks)
      concent.file.chunks = totalChunks; // 将总片段数保存到file对象中
      let uploaded = 0 // 已上传块数
      /*return this.calculateMD5(concent.file)
        .then(md5 => {*/
          let time = new Date().getTime();
          let name2 = concent.file.name;
          let index = name2.lastIndexOf(".");
          name2 = name2.substring(0,index)+time+name2.substring(index,name2.length);
          // 将文件切分为多个片段
          const chunks = [];
          for (let i = 0; i < totalChunks; i++) {
            const start = i * this.chunkSize * 1024 * 1024;
            const end = Math.min(start + this.chunkSize * 1024 * 1024, concent.file.size);
            // chunks.push(concent.file.slice(start, end));
            chunks.push(
              new Promise((resolve, reject) => {
                const formData = new FormData();
                formData.append("file", concent.file.slice(start, end),name2);
                formData.append("chunk", i + 1);
                formData.append("type",this.menuName.includes("大事记")?1:2);  // 1 大事记 2 组织沿革
                formData.append("modeEnum", "RANDOM_ACCESS");
                //formData.append("chunkSize", concent.file.chunkSize); //分片大小
                formData.append("chunkSize", this.chunkSize); //分片大小
                formData.append("chunks", concent.file.chunks); // 总分片数
                formData.append("mj", this.fileMJ); // 总分片数
                //console.log(concent.file.chunkSize,"-----");
                //console.log(concent.file.chunks,"=====");
                formData.append("md5", this.userId + '_' + new Date().getTime()); // md5值
                fileUpload(formData).then(response => {
                  resolve(response); // 将上传结果传递给 Promise 的 resolve
                }).catch(error => {
                  reject(error); // 将错误信息传递给 Promise 的 reject
                });
              })
            )
          }
          return Promise.all(chunks).then(responses => {
            this.$modal.closeLoading();
            this.getList();
          }).catch(error => {
              console.error("错误:", error);
              throw error; // 抛出错误，以便后续可以捕获并处理
            }); // 等待所有分片上传完成
        /*})
        .then(responses => {
          this.$modal.closeLoading();
          this.getList();
        })*/

    },

  }
};
</script>
